package com.study.scapp.info.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

    //构建网络请求：发出和接收
    public static String request(String api){
        try {
            //发起网络请求
            URL url = new URL(api);
            //打开相应api的请求
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //获得响应码
            int responseCode = httpURLConnection.getResponseCode();
            //判断相应状态
            if (200 <= responseCode && responseCode <= 299){
                //返回正常，读取返回内容
                try (InputStream inputStream = httpURLConnection.getInputStream()){
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String input;
                    StringBuilder sb = new StringBuilder();
                    while ((input = bufferedReader.readLine()) != null ){
                        sb.append(input);
                    }
                    String result = sb.toString();
                    return result;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                //返回异常
                System.out.println("服务器相应异常，请检查指令或网络连接状况");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }



}

